package com.zhs;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
public class TransactionConsumer {
    public static void main(String[]args) throws Exception{
        DefaultMQPushConsumer consumer=new DefaultMQPushConsumer("transaction_consumer_group");
        consumer.setNamesrvAddr("192.168.0.241:9876");
        //制定消费者从什么位置消费
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
        //订阅topic_java主题下所有消息
        consumer.subscribe("topic_transaction","*");

        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
               for(MessageExt ext:list){
                   log.info("消费者接收到消息："+ext);
                   log.info("接收到的消息标签:{}",new String(ext.getTags()));
                   log.info("接收到的消息内容:{}",new String(ext.getBody()));
               }
                try {
                   //模拟业务处理
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        //必须start后才能使用
        consumer.start();
        System.out.println("consumer 已经启动");
    }
}
